<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">WebUSB API</h1>
        <p class="text-gray-300 text-lg">
          直接访问 USB 设备，实现硬件交互和控制
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 WebUSB API。此功能需要 Chrome 61+、Edge 79+ 或其他支持的浏览器。
        </p>
        <p class="text-yellow-400 text-sm mt-2">
          注意：WebUSB API 需要 HTTPS 环境（或 localhost）才能使用。
        </p>
      </div>

      <template v-if="isSupported">
        <!-- USB 设备连接 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-usb text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">USB 设备管理</h2>
          </div>

          <div class="space-y-6">
            <!-- 设备连接 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">设备连接</h3>

              <div class="flex gap-3 mb-4">
                <button
                  @click="requestDevice"
                  class="tech-button flex-1"
                >
                  <i class="i-carbon-usb mr-2"></i>
                  请求连接 USB 设备
                </button>

                <button
                  @click="getDevices"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
                >
                  <i class="i-carbon-renew mr-2"></i>
                  刷新设备列表
                </button>
              </div>

              <div class="bg-gray-900 rounded-lg p-4">
                <p class="text-gray-400 text-sm">
                  点击"请求连接 USB 设备"按钮，浏览器会显示可用的 USB 设备列表供您选择。
                </p>
                <p class="text-yellow-400 text-sm mt-2">
                  ⚠️ 需要用户明确授权才能访问 USB 设备
                </p>
              </div>
            </div>

            <!-- 已连接设备列表 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">已授权设备 ({{ devices.length }})</h3>

              <div v-if="devices.length === 0" class="text-center py-8 text-gray-400">
                暂无已授权的 USB 设备
              </div>

              <div v-else class="space-y-4">
                <div
                  v-for="(device, index) in devices"
                  :key="index"
                  class="bg-gray-900 rounded-lg p-4"
                >
                  <div class="flex items-start justify-between mb-3">
                    <div class="flex-1">
                      <h4 class="text-white font-semibold text-lg mb-1">
                        {{ device.productName || '未命名设备' }}
                      </h4>
                      <p class="text-gray-400 text-sm">
                        {{ device.manufacturerName || '未知制造商' }}
                      </p>
                    </div>
                    <span
                      :class="[
                        device.opened ? 'bg-green-600' : 'bg-gray-600',
                        'px-3 py-1 rounded text-xs text-white'
                      ]"
                    >
                      {{ device.opened ? '已打开' : '未打开' }}
                    </span>
                  </div>

                  <div class="grid grid-cols-2 gap-2 text-sm mb-3">
                    <div class="text-gray-400">
                      厂商 ID: <span class="text-white">0x{{ device.vendorId.toString(16).padStart(4, '0') }}</span>
                    </div>
                    <div class="text-gray-400">
                      产品 ID: <span class="text-white">0x{{ device.productId.toString(16).padStart(4, '0') }}</span>
                    </div>
                    <div class="text-gray-400">
                      序列号: <span class="text-white">{{ device.serialNumber || 'N/A' }}</span>
                    </div>
                    <div class="text-gray-400">
                      USB 版本: <span class="text-white">{{ getUSBVersion(device.usbVersionMajor, device.usbVersionMinor) }}</span>
                    </div>
                  </div>

                  <div class="flex gap-2">
                    <button
                      v-if="!device.opened"
                      @click="openDevice(device)"
                      class="tech-button text-sm"
                    >
                      <i class="i-carbon-play-filled mr-1"></i>
                      打开设备
                    </button>

                    <button
                      v-else
                      @click="closeDevice(device)"
                      class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-close mr-1"></i>
                      关闭设备
                    </button>

                    <button
                      @click="showDeviceInfo(device)"
                      class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-information mr-1"></i>
                      详细信息
                    </button>

                    <button
                      @click="forgetDevice(device)"
                      class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-trash-can mr-1"></i>
                      移除
                    </button>
                  </div>

                  <!-- 配置信息 -->
                  <div v-if="device.opened && device.configurations.length > 0" class="mt-4 pt-4 border-t border-gray-800">
                    <h5 class="text-white font-semibold text-sm mb-2">设备配置</h5>
                    <div class="text-xs text-gray-400">
                      <p>配置数量: {{ device.configurations.length }}</p>
                      <p v-if="device.configuration">当前配置: {{ device.configuration.configurationValue }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 数据传输 -->
        <div v-if="selectedDevice && selectedDevice.opened" class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-data-transfer text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">数据传输</h2>
          </div>

          <div class="space-y-6">
            <!-- 控制传输 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">控制传输</h3>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-300 mb-2 text-sm">请求类型:</label>
                  <select
                    v-model="controlTransfer.requestType"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option value="standard">Standard</option>
                    <option value="class">Class</option>
                    <option value="vendor">Vendor</option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">接收方:</label>
                  <select
                    v-model="controlTransfer.recipient"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option value="device">Device</option>
                    <option value="interface">Interface</option>
                    <option value="endpoint">Endpoint</option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">请求码 (bRequest):</label>
                  <input
                    v-model.number="controlTransfer.request"
                    type="number"
                    min="0"
                    max="255"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">值 (wValue):</label>
                  <input
                    v-model.number="controlTransfer.value"
                    type="number"
                    min="0"
                    max="65535"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">索引 (wIndex):</label>
                  <input
                    v-model.number="controlTransfer.index"
                    type="number"
                    min="0"
                    max="65535"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">长度:</label>
                  <input
                    v-model.number="controlTransfer.length"
                    type="number"
                    min="0"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>
              </div>

              <div class="flex gap-3">
                <button
                  @click="sendControlTransferIn"
                  class="tech-button flex-1"
                >
                  <i class="i-carbon-download mr-2"></i>
                  控制传输 (IN)
                </button>

                <button
                  @click="sendControlTransferOut"
                  class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors flex-1"
                >
                  <i class="i-carbon-upload mr-2"></i>
                  控制传输 (OUT)
                </button>
              </div>
            </div>

            <!-- 批量传输 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">批量传输</h3>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-300 mb-2 text-sm">端点号:</label>
                  <input
                    v-model.number="bulkTransfer.endpointNumber"
                    type="number"
                    min="1"
                    max="15"
                    placeholder="1-15"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">数据长度:</label>
                  <input
                    v-model.number="bulkTransfer.length"
                    type="number"
                    min="0"
                    placeholder="字节数"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>
              </div>

              <div class="flex gap-3">
                <button
                  @click="sendBulkTransferIn"
                  class="tech-button flex-1"
                >
                  <i class="i-carbon-download mr-2"></i>
                  批量传输 (IN)
                </button>

                <button
                  @click="sendBulkTransferOut"
                  class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors flex-1"
                >
                  <i class="i-carbon-upload mr-2"></i>
                  批量传输 (OUT)
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 传输日志 -->
        <div v-if="transferLogs.length > 0" class="tech-card mb-8">
          <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-semibold text-white">传输日志</h2>
            <button
              @click="clearLogs"
              class="text-red-400 hover:text-red-300 text-sm"
            >
              <i class="i-carbon-clean mr-1"></i>
              清空日志
            </button>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="space-y-2 max-h-96 overflow-y-auto font-mono text-sm">
              <div
                v-for="(log, index) in transferLogs.slice().reverse()"
                :key="index"
                :class="[
                  log.type === 'success' ? 'border-green-600' :
                  log.type === 'error' ? 'border-red-600' :
                  'border-blue-600',
                  'border-l-4 bg-gray-900 rounded p-3'
                ]"
              >
                <div class="flex justify-between items-start mb-1">
                  <span
                    :class="[
                      log.type === 'success' ? 'text-green-400' :
                      log.type === 'error' ? 'text-red-400' :
                      'text-blue-400'
                    ]"
                    class="font-semibold"
                  >
                    {{ log.operation }}
                  </span>
                  <span class="text-gray-500 text-xs">{{ log.timestamp }}</span>
                </div>
                <div class="text-gray-300">{{ log.message }}</div>
                <div v-if="log.data" class="text-gray-400 text-xs mt-1">
                  数据: {{ log.data }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 常见 USB 设备 -->
        <div class="tech-card mb-8">
          <h2 class="text-2xl font-semibold mb-6 text-white">常见 USB 设备类型</h2>

          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div
              v-for="deviceType in commonDeviceTypes"
              :key="deviceType.name"
              class="bg-gray-800 rounded-lg p-4"
            >
              <i :class="deviceType.icon" class="text-3xl text-tech-accent mb-3 block"></i>
              <h4 class="text-white font-semibold mb-2">{{ deviceType.name }}</h4>
              <p class="text-gray-400 text-sm mb-2">{{ deviceType.description }}</p>
              <div class="text-xs text-gray-500">
                <p>类代码: {{ deviceType.classCode }}</p>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 61+, Edge 79+, Opera 48+</p>
            <p class="text-sm text-yellow-400 mt-1">注意：需要 HTTPS 环境（或 localhost）</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.usb.requestDevice()</code> - 请求访问设备</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.usb.getDevices()</code> - 获取已授权设备</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.open()</code> - 打开设备</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.close()</code> - 关闭设备</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.selectConfiguration()</code> - 选择配置</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.claimInterface()</code> - 声明接口</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.controlTransferIn/Out()</code> - 控制传输</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">device.transferIn/Out()</code> - 批量/中断传输</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">基本用法</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// 请求访问 USB 设备</span>
<span class="text-blue-400">const</span> device = <span class="text-blue-400">await</span> navigator.usb.requestDevice({
  filters: [{ vendorId: <span class="text-orange-400">0x2341</span> }] <span class="text-gray-500">// Arduino</span>
});

<span class="text-gray-500">// 打开设备</span>
<span class="text-blue-400">await</span> device.open();
<span class="text-blue-400">await</span> device.selectConfiguration(<span class="text-orange-400">1</span>);
<span class="text-blue-400">await</span> device.claimInterface(<span class="text-orange-400">0</span>);

<span class="text-gray-500">// 控制传输</span>
<span class="text-blue-400">const</span> result = <span class="text-blue-400">await</span> device.controlTransferIn({
  requestType: <span class="text-green-400">'vendor'</span>,
  recipient: <span class="text-green-400">'device'</span>,
  request: <span class="text-orange-400">0x01</span>,
  value: <span class="text-orange-400">0x00</span>,
  index: <span class="text-orange-400">0x00</span>
}, <span class="text-orange-400">64</span>);

<span class="text-gray-500">// 关闭设备</span>
<span class="text-blue-400">await</span> device.close();</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">传输类型</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><strong>控制传输：</strong>用于设备配置和命令发送</li>
              <li><strong>批量传输：</strong>用于大量数据传输（如打印机、存储设备）</li>
              <li><strong>中断传输：</strong>用于小量低延迟数据（如键盘、鼠标）</li>
              <li><strong>等时传输：</strong>用于实时数据流（如音频、视频）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>Arduino 和开发板编程</li>
              <li>3D 打印机控制</li>
              <li>硬件调试工具</li>
              <li>自定义 USB 设备通信</li>
              <li>科研仪器数据采集</li>
              <li>医疗设备集成</li>
              <li>工业自动化控制</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">安全性</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>需要用户明确授权才能访问设备</li>
              <li>只能访问已授权的特定设备</li>
              <li>需要 HTTPS 环境（或 localhost）</li>
              <li>某些设备类型受限制（如 HID、音频、视频）</li>
              <li>权限可以被用户随时撤销</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>始终检查浏览器是否支持 WebUSB</li>
              <li>妥善处理用户拒绝授权的情况</li>
              <li>使用合适的传输类型和端点</li>
              <li>正确处理设备断开连接事件</li>
              <li>及时释放接口和关闭设备</li>
              <li>实现错误重试和恢复机制</li>
              <li>提供清晰的设备连接指引</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">限制说明</h4>
            <div class="text-sm space-y-1">
              <p>以下设备类型受保护，WebUSB 无法访问：</p>
              <ul class="list-disc list-inside ml-4">
                <li>USB HID 设备（键盘、鼠标）</li>
                <li>USB 音频设备</li>
                <li>USB 视频设备</li>
                <li>USB 智能卡读卡器</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 类型定义
interface TransferLog {
  operation: string
  message: string
  type: 'info' | 'success' | 'error'
  timestamp: string
  data?: string
}

interface DeviceType {
  name: string
  description: string
  icon: string
  classCode: string
}

// 响应式状态
const isSupported = ref(false)
const devices = ref<USBDevice[]>([])
const selectedDevice = ref<USBDevice | null>(null)
const transferLogs = ref<TransferLog[]>([])

// 控制传输参数
const controlTransfer = ref({
  requestType: 'vendor' as USBRequestType,
  recipient: 'device' as USBRecipient,
  request: 0,
  value: 0,
  index: 0,
  length: 64
})

// 批量传输参数
const bulkTransfer = ref({
  endpointNumber: 1,
  length: 64
})

// 常见设备类型
const commonDeviceTypes: DeviceType[] = [
  { name: 'Arduino', description: '开发板和微控制器', icon: 'i-carbon-chip', classCode: '0xFF (Vendor)' },
  { name: '3D 打印机', description: '3D 打印设备', icon: 'i-carbon-3d-print-mesh', classCode: '0x07 (Printer)' },
  { name: '串口转换器', description: 'USB 转串口适配器', icon: 'i-carbon-data-base', classCode: '0x02 (CDC)' },
  { name: '存储设备', description: 'U盘和移动硬盘', icon: 'i-carbon-data-storage', classCode: '0x08 (Mass Storage)' },
  { name: '摄像头', description: 'USB 摄像头设备', icon: 'i-carbon-video', classCode: '0x0E (Video)' },
  { name: '自定义设备', description: '自定义 USB 硬件', icon: 'i-carbon-application', classCode: '0xFF (Vendor)' }
]

// 初始化
onMounted(() => {
  isSupported.value = !!(navigator.usb)
  
  if (isSupported.value) {
    // 监听设备连接/断开
    navigator.usb.addEventListener('connect', handleDeviceConnect)
    navigator.usb.addEventListener('disconnect', handleDeviceDisconnect)
    
    // 获取已授权设备
    getDevices()
  }
})

// 清理
onUnmounted(() => {
  if (isSupported.value) {
    navigator.usb.removeEventListener('connect', handleDeviceConnect)
    navigator.usb.removeEventListener('disconnect', handleDeviceDisconnect)
  }
})

// 请求设备
const requestDevice = async () => {
  try {
    const device = await navigator.usb.requestDevice({
      filters: [] // 空过滤器显示所有设备
    })
    
    addLog('请求设备', `已授权访问设备: ${device.productName}`, 'success')
    await getDevices()
  } catch (error) {
    addLog('请求设备', `请求失败: ${error}`, 'error')
  }
}

// 获取已授权设备
const getDevices = async () => {
  try {
    devices.value = await navigator.usb.getDevices()
    addLog('获取设备', `找到 ${devices.value.length} 个已授权设备`, 'info')
  } catch (error) {
    addLog('获取设备', `获取失败: ${error}`, 'error')
  }
}

// 打开设备
const openDevice = async (device: USBDevice) => {
  try {
    await device.open()
    
    // 选择第一个配置
    if (device.configurations.length > 0) {
      await device.selectConfiguration(device.configurations[0].configurationValue)
      
      // 声明第一个接口
      if (device.configuration && device.configuration.interfaces.length > 0) {
        await device.claimInterface(0)
      }
    }
    
    selectedDevice.value = device
    await getDevices() // 刷新设备状态
    addLog('打开设备', `设备 ${device.productName} 已打开`, 'success')
  } catch (error) {
    addLog('打开设备', `打开失败: ${error}`, 'error')
  }
}

// 关闭设备
const closeDevice = async (device: USBDevice) => {
  try {
    if (device.opened) {
      await device.close()
      
      if (selectedDevice.value === device) {
        selectedDevice.value = null
      }
      
      await getDevices() // 刷新设备状态
      addLog('关闭设备', `设备 ${device.productName} 已关闭`, 'success')
    }
  } catch (error) {
    addLog('关闭设备', `关闭失败: ${error}`, 'error')
  }
}

// 移除设备授权
const forgetDevice = async (device: USBDevice) => {
  try {
    if (device.opened) {
      await device.close()
    }
    
    await device.forget()
    await getDevices()
    addLog('移除设备', `已移除设备 ${device.productName} 的授权`, 'success')
  } catch (error) {
    addLog('移除设备', `移除失败: ${error}`, 'error')
  }
}

// 显示设备详细信息
const showDeviceInfo = (device: USBDevice) => {
  const info = `
设备名称: ${device.productName || 'N/A'}
制造商: ${device.manufacturerName || 'N/A'}
序列号: ${device.serialNumber || 'N/A'}
厂商 ID: 0x${device.vendorId.toString(16).padStart(4, '0')}
产品 ID: 0x${device.productId.toString(16).padStart(4, '0')}
设备类: ${device.deviceClass}
设备子类: ${device.deviceSubclass}
USB 版本: ${getUSBVersion(device.usbVersionMajor, device.usbVersionMinor)}
配置数量: ${device.configurations.length}
  `.trim()
  
  alert(info)
}

// 控制传输 IN
const sendControlTransferIn = async () => {
  if (!selectedDevice.value) return

  try {
    const result = await selectedDevice.value.controlTransferIn({
      requestType: controlTransfer.value.requestType,
      recipient: controlTransfer.value.recipient,
      request: controlTransfer.value.request,
      value: controlTransfer.value.value,
      index: controlTransfer.value.index
    }, controlTransfer.value.length)

    const data = new Uint8Array(result.data?.buffer || [])
    const dataStr = Array.from(data).map(b => '0x' + b.toString(16).padStart(2, '0')).join(' ')
    
    addLog('控制传输 IN', `接收到 ${data.length} 字节`, 'success', dataStr)
  } catch (error) {
    addLog('控制传输 IN', `传输失败: ${error}`, 'error')
  }
}

// 控制传输 OUT
const sendControlTransferOut = async () => {
  if (!selectedDevice.value) return

  try {
    const data = new Uint8Array([0x01, 0x02, 0x03, 0x04])
    
    const result = await selectedDevice.value.controlTransferOut({
      requestType: controlTransfer.value.requestType,
      recipient: controlTransfer.value.recipient,
      request: controlTransfer.value.request,
      value: controlTransfer.value.value,
      index: controlTransfer.value.index
    }, data)

    addLog('控制传输 OUT', `发送 ${result.bytesWritten} 字节`, 'success')
  } catch (error) {
    addLog('控制传输 OUT', `传输失败: ${error}`, 'error')
  }
}

// 批量传输 IN
const sendBulkTransferIn = async () => {
  if (!selectedDevice.value) return

  try {
    const result = await selectedDevice.value.transferIn(
      bulkTransfer.value.endpointNumber,
      bulkTransfer.value.length
    )

    const data = new Uint8Array(result.data?.buffer || [])
    const dataStr = Array.from(data).map(b => '0x' + b.toString(16).padStart(2, '0')).join(' ')
    
    addLog('批量传输 IN', `接收到 ${data.length} 字节`, 'success', dataStr)
  } catch (error) {
    addLog('批量传输 IN', `传输失败: ${error}`, 'error')
  }
}

// 批量传输 OUT
const sendBulkTransferOut = async () => {
  if (!selectedDevice.value) return

  try {
    const data = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]) // "Hello"
    
    const result = await selectedDevice.value.transferOut(
      bulkTransfer.value.endpointNumber,
      data
    )

    addLog('批量传输 OUT', `发送 ${result.bytesWritten} 字节`, 'success')
  } catch (error) {
    addLog('批量传输 OUT', `传输失败: ${error}`, 'error')
  }
}

// 设备连接事件
const handleDeviceConnect = (event: USBConnectionEvent) => {
  addLog('设备连接', `设备已连接: ${event.device.productName}`, 'info')
  getDevices()
}

// 设备断开事件
const handleDeviceDisconnect = (event: USBConnectionEvent) => {
  addLog('设备断开', `设备已断开: ${event.device.productName}`, 'info')
  
  if (selectedDevice.value === event.device) {
    selectedDevice.value = null
  }
  
  getDevices()
}

// 添加日志
const addLog = (operation: string, message: string, type: TransferLog['type'], data?: string) => {
  transferLogs.value.push({
    operation,
    message,
    type,
    timestamp: new Date().toLocaleTimeString('zh-CN'),
    data
  })
}

// 清空日志
const clearLogs = () => {
  transferLogs.value = []
}

// 获取 USB 版本
const getUSBVersion = (major: number, minor: number): string => {
  return `${major}.${minor}`
}
</script>

<style scoped>
/* 自定义样式 */
</style>

